package com.example.demo.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 日期工具类封装
 * Created by gan on 2018/9/12 22:57.
 */
public class DateUtils {


    public static void main(String[] args) {
        List<String> dates = new ArrayList<>();
        dates.add("2018-01");
        dates.add("2018-02");
        dates.add("2018-09");

        String currentDate = "2018-01-23";
        String substring = currentDate.substring(0, currentDate.lastIndexOf('-'));
        System.out.println(substring);
        for (int i = 0; i < dates.size(); i++) {
            if (dates.get(i).equals(substring)) {
                System.out.println(dates.get(i));
            }
        }


        //获取前七天的日期
        Date dateBefore = getDateBefore(new Date(), 7);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(sf.format(dateBefore));

    }


    /**
     * 得到几天前的时间
     *
     * @param d
     * @param day
     * @return
     */
    public static Date getDateBefore(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.getTime();

    }
}
